package com.evon.yardmanagement.security;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;

import com.evon.yardmanagement.dao.RoleDAO;
import com.evon.yardmanagement.dao.YardDAO;
import com.evon.yardmanagement.model.Role;
import com.evon.yardmanagement.model.User;
import com.evon.yardmanagement.model.Vendor;
import com.evon.yardmanagement.model.Yard;

/**
 * Class responsible for managing the authorization and security constraints
 * within the application.
 * 
 * @author vgaurav
 * 
 */
public class YardSecurityManager {

	/**
	 * Return the company id of the current logged in user.
	 * 
	 * @return
	 */
	public static Vendor getCurrentVendor() {
		User loggedInUser = (User) SecurityUtils.getSubject().getSession()
				.getAttribute("CURRENT_USER");
		return loggedInUser.getVendor();

	}

	/**
	 * Return the all accessible yard for the current logged in user.
	 * 
	 * @return
	 */
	public static Set<Yard> getAccessibleYards() {
		User loggedInUser = (User) SecurityUtils.getSubject().getSession()
				.getAttribute("CURRENT_USER");
		if (SecurityUtils.getSecurityManager().hasRole(
				SecurityUtils.getSubject().getPrincipals(), "SUPER_ADMIN")) {
			return new HashSet<Yard>(new YardDAO().findAll());
		}
		return loggedInUser.getAccessibleYards();
	}

	/**
	 * Return the role of the user in the current yard.
	 * 
	 * @param yardId
	 * @return
	 */
	public static Role getRoleForYard(int yardId) {
		User loggedInUser = (User) SecurityUtils.getSubject().getSession()
				.getAttribute("CURRENT_USER");

		new RoleDAO().getRole(yardId, loggedInUser.getId());
		return null;
	}

	public static void main(String[] ars) {
		List<Role> roles = new RoleDAO().getRole(101, 101);
		for (Role role : roles) {
			System.err.println("Role name -" + role.getName());
		}
	}

}
